package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.entity.*;
import com.bbs.mapper.IBBSPostCategoryMapper;
import com.bbs.mapper.IBBSPostMapper;
import com.bbs.mapper.IBBSUserMapper;
import com.bbs.service.IBBSPostService;
import com.bbs.util.BeanUtil;
import com.bbs.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class BBSPostServiceImpl implements IBBSPostService {
    @Autowired
    private IBBSPostMapper bbsPostMapper;
    @Autowired
    private IBBSUserMapper bbsUserMapper;
    @Autowired
    private IBBSPostCategoryMapper bbsPostCategoryMapper;

    /**
     * 发布帖子
     * @param bbsPost
     * @return
     * @author: Toin
     */
    @Override
    public int savePost(BBSPost bbsPost) {
        //如果账号不存在或状态码为1
        // 账号封禁
        BBSUser bbsUser = bbsUserMapper.selectOne(
                new LambdaQueryWrapper<BBSUser>()
                .eq(BBSUser::getUserId, bbsPost.getPublishUserId())
        );
        if (bbsUser == null && bbsUser.getUserStatus() == 1) {
            return 0;
        }

        BBSPostCategory bbsPostCategory = bbsPostCategoryMapper.selectOne(
                new LambdaQueryWrapper<BBSPostCategory>()
                .eq(BBSPostCategory::getCategoryId, bbsPost.getPostCategoryId())
        );
        if(bbsPostCategory == null){
            //分类错误
            return 0;
        }
        return bbsPostMapper.insert(bbsPost);
    }

    /**
     * 通过帖子ID获取帖子详情
     * @param bbsPostId
     * @return
     */
    @Override
    public BBSPost getBBSPostById(Long bbsPostId) {
        return bbsPostMapper.selectOne(
                new LambdaQueryWrapper<BBSPost>()
                .eq(BBSPost::getPostId, bbsPostId)
        );
    }
    /*
     * 获取帖子内容的详情
     * */
    @Override
    public BBSPost getBBSPostForDetail(Long bbsPostId) {
        BBSPost bbsPost = bbsPostMapper.selectOne(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPostId,bbsPostId)
        );
        if (bbsPost != null) {
            bbsPost.setPostViews(bbsPost.getPostViews() + 1);
            bbsPostMapper.update(bbsPost, new UpdateWrapper<BBSPost>()
                    .eq("post_id", bbsPost.getPostId())
                    .set("post_views", bbsPost.getPostViews())
            );
        }
        return bbsPost;
    }

    /**
     * 更新帖子
     * @param bbsPost
     * @return
     */
    @Override
    public int updateBBSPost(BBSPost bbsPost) {
        BBSUser bbsUser = bbsUserMapper.selectOne(
                new LambdaQueryWrapper<BBSUser>()
                        .eq(BBSUser::getUserId, bbsPost.getPublishUserId())
        );
        if (bbsUser == null || bbsUser.getUserStatus() == 1) {
            //账号封禁
            return 0;
        }
        BBSPostCategory bbsPostCategory = bbsPostCategoryMapper.selectOne(
                new LambdaQueryWrapper<BBSPostCategory>()
                        .eq(BBSPostCategory::getCategoryId, bbsPost.getPostCategoryId())
        );
        if (bbsPostCategory == null) {
            //分类数据错误
            return 0;
        }
        return bbsPostMapper.update(bbsPost, new UpdateWrapper<BBSPost>()
                .eq("post_id", bbsPost.getPostId())
                .set("post_category_id", bbsPost.getPostCategoryId())
                .set("post_title", bbsPost.getPostTitle())
                .set("post_content", bbsPost.getPostContent()));
    }


    /**
     * 删除帖子
     * @param userId
     * @param postId
     * @return
     */
    @Override
    public int delBBSPost(Long userId, Long postId) {
        BBSUser bbsUser = bbsUserMapper.selectOne(
                new LambdaQueryWrapper<BBSUser>()
                        .eq(BBSUser::getUserId, userId)
        );
        if (bbsUser == null || bbsUser.getUserStatus() == 1) {
            //账号封禁
            return 0;
        }

        BBSPost bbsPost = bbsPostMapper.selectOne(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPostId, postId)
        );
        if (bbsPost != null && bbsPost.getPublishUserId().equals(userId)) {
            return bbsPostMapper.delete(
                    new LambdaQueryWrapper<BBSPost>()
                            .eq(BBSPost::getPostId, postId)
            );
        }
        return 0;
    }

    /**
     * 获取帖子列表
     * @param params
     * @return
     */
    @Override
    public PageResult getBBSPostPageForIndex(Map<String, Object> params) {
        // 查询首页帖子总条数
        int total = bbsPostMapper.selectCount(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPostStatus, 1)
        ).intValue();

        // 创建分页对象
        int currentPage = (int) params.get("page");
        int pageSize = (int) params.get("limit");
        Page<BBSPost> page = new Page<>(currentPage, pageSize);

        // 创建条件查询构造器
        QueryWrapper<BBSPost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_status", 1);

        // 类别过滤
        if (params.get("categoryId") != null && !params.get("categoryId").toString().isEmpty()) {
            queryWrapper.eq("post_category_id", params.get("categoryId"));
        }
        // 关键字过滤
        if (params.get("keyword") != null && !params.get("keyword").toString().isEmpty()) {
            queryWrapper.like("post_title", params.get("keyword"));
        }
        // 时间段过滤
        if (params.get("period") != null) {
            String period = params.get("period").toString();
            if ("hot7".equals(period)) {
                queryWrapper.gt("create_time", LocalDateTime.now().minusDays(7));
            } else if ("hot30".equals(period)) {
                queryWrapper.gt("create_time", LocalDateTime.now().minusDays(30));
            }
        }
        // 排序
        if (params.get("orderBy") != null) {
            String orderBy = params.get("orderBy").toString();
            if ("new".equals(orderBy)) {
                queryWrapper.orderByDesc("post_id");
            } else if ("comment".equals(orderBy)) {
                queryWrapper.orderByDesc("post_comments");
            }
        } else {
            queryWrapper.orderByDesc("last_update_time")
                    .orderByDesc("post_views")
                    .orderByDesc("post_comments");
        }

        // 查询分页数据
        Page<BBSPost> bbsPostPage = bbsPostMapper.selectPage(page, queryWrapper);

        // 将bbsPostPage转换为List列表
        List<BBSPost> bbsPostList = bbsPostPage.getRecords();

        List<BBSPostListEntity> bbsPostListEntities = new ArrayList<>();
        // 数据格式转换
        if (!CollectionUtils.isEmpty(bbsPostList)) {
            // 如果首页帖子列表不为空 将bbsPostList列表中的元素复制到bbsPostListEntities列表中
            bbsPostListEntities = BeanUtil.copyList(bbsPostList, BBSPostListEntity.class);

            List<Long> userIds = bbsPostListEntities.stream().map(BBSPostListEntity::getPublishUserId).collect(Collectors.toList());
            // 查询发布者数据
            List<BBSUser> bbsUsers = bbsUserMapper.selectList(
                    new LambdaQueryWrapper<BBSUser>()
                            .in(BBSUser::getUserId, userIds)
            );

            if (!CollectionUtils.isEmpty(bbsUsers)) {
                Map<Long, BBSUser> bbsUserMap = bbsUsers.stream()
                        .collect(Collectors.toMap(BBSUser::getUserId, Function.identity(), (entity1, entity2) -> entity1));
                for (BBSPostListEntity bbsPostListEntity : bbsPostListEntities) {
                    // 判断bbsUserMap中是否包含指定的键
                    if (bbsUserMap.containsKey(bbsPostListEntity.getPublishUserId())) {
                        // 设置头像字段和昵称字段
                        BBSUser tempUser = bbsUserMap.get(bbsPostListEntity.getPublishUserId());
                        bbsPostListEntity.setHeadImgUrl(tempUser.getHeadImgUrl());
                        bbsPostListEntity.setNickName(tempUser.getNickName());
                    }
                }
            }
        }

        PageResult pageResult = new PageResult(bbsPostListEntities, total, pageSize, currentPage);
        return pageResult;
    }

    /**
     * 获取近期热议帖子列表
     * @return
     */
    @Override
    public List getHotTopicBBSPostList() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取七天前的时间
        LocalDateTime sevenDaysAgo = now.minusDays(7);

        List<BBSPost> bbsPostList = bbsPostMapper.selectList(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPostStatus, 1)
                        .orderByDesc(BBSPost::getPostComments)
                        .last("limit 10")
                        .between(BBSPost::getCreateTime, sevenDaysAgo, now)
        );
        //创建热议帖子的新列表 该实体类中仅有帖子ID、标题、评论数三个属性
        List<HotTopicBBSPostListEntity> hotTopicBBSPostList = new ArrayList<>();
        //判断获取到的热议帖子是否为空
        if (!CollectionUtils.isEmpty(bbsPostList)){
            //如果热议帖子列表不为空 将bbsPostList列表中的元素复制到hotTopicBBSPostList列表中
            hotTopicBBSPostList = BeanUtil.copyList(bbsPostList, HotTopicBBSPostListEntity.class);
        }
        return hotTopicBBSPostList;
    }

    @Override
    public List<BBSPost> getMyBBSPostList(Long userId) {
        return bbsPostMapper.selectList(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPublishUserId, userId)
                        .orderByDesc(BBSPost::getPostId)
        );
    }


    @Override
    public List<BBSPost> getRecentPostListByUserId(Long userId) {
        return bbsPostMapper.selectList(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPublishUserId, userId)
                        .orderByDesc(BBSPost::getCreateTime)
                        .last("limit 10")
        );
    }
}
